package com.weiz.service.Impl;

import com.weiz.domain.SysRole;
import com.weiz.domain.SysUser;
import com.weiz.dto.LoginUser;
import com.weiz.dto.LoginRole;
import com.weiz.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component(value="CustomUserDetailsService")
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    public LoginUser loadUserByUsername(String name) throws UsernameNotFoundException {
        SysUser sysUser = sysUserRepository.findUserByUsername(name);
        LoginUser loginUser = new LoginUser(sysUser.getId(),sysUser.getUsername(),sysUser.getPassword());
        List<SysRole> roleList = sysUserRepository.findRolesByUsername(name);
        if (loginUser == null || roleList==null || roleList.size()==0) {
            throw new UsernameNotFoundException(String.format("No userDetail found with username '%s'.", name));
        }
        LoginRole loginRole = LoginRole.builder().name(roleList.get(0).getName()).build();
        loginUser.setLoginRole(loginRole);
        return loginUser;
    }
}
